﻿using In66.Net.Repository.IRepositories.ISqlSugar;

namespace Usr.Api.Applications.BloomFilters
{
    public class CacheKeyBloomFilter : AbstractBloomFilter
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly IOptions<RedisConfig> _cacheOptions;

        public CacheKeyBloomFilter(
            IOptions<RedisConfig> cacheOptions,
            IRedisProvider redisProvider,
            IDistributedLocker distributedLocker,
            IServiceProvider serviceProvider)
            : base(redisProvider, distributedLocker)
        {
            _serviceProvider = serviceProvider;
            _cacheOptions = cacheOptions;
        }

        public override string Name => _cacheOptions.Value.PenetrationSetting.BloomFilterSetting.Name;

        public override double ErrorRate => _cacheOptions.Value.PenetrationSetting.BloomFilterSetting.ErrorRate;

        public override int Capacity => _cacheOptions.Value.PenetrationSetting.BloomFilterSetting.Capacity;

        public override async Task InitAsync()
        {
            var exists = await ExistsBloomFilterAsync();
            if (!exists)
            {
                var values = new List<string>()
            {
                CachingConsts.MenuListCacheKey,
                CachingConsts.MenuTreeListCacheKey,
                CachingConsts.MenuRelationCacheKey,
                CachingConsts.MenuCodesCacheKey,
                CachingConsts.DetpListCacheKey,
                CachingConsts.DetpTreeListCacheKey,
                CachingConsts.DetpSimpleTreeListCacheKey,
                CachingConsts.RoleListCacheKey
            };

                using var scope = _serviceProvider.CreateScope();
                var repository = scope.ServiceProvider.GetRequiredService<ISugarBaseRepository<Models.Entities.User>>();
                var ids = repository.QueryListByClause(p => true)
                                                        .Select(x => x.Id)
                                                        .ToList();
                if (ids.IsNotNullOrEmpty())
                {
                    values.AddRange(ids.Select(x => string.Concat(CachingConsts.UserValidatedInfoKeyPrefix, CachingConsts.LinkChar, x)));
                }

                await InitAsync(values);
            }
        }
    }
}
